/**
 * Created by luolinlan on 19/11/18.
 */
/* import moment from 'moment'*/

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

export function formatTime(time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

export function returnZore(data) {
  return data < 10 ? '0' + data : data
}

/* export function formatDatePicker(date) {
  /!* let d = new Date(date)
  return d.getFullYear()+"-"+returnZore(d.getMonth()+1)+"-"+returnZore(d.getDate())+" "+returnZore(d.getHours())+":"+returnZore(d.getMinutes())*!/
  return moment(date).format('YYYY-MM-DD')
}

export function formatDateTime(date) {
  return moment(date).format('YYYY-MM-DD HH:mm:ss')
}

export function formatDate(date) {
  /!* let d = new Date(date)
   return d.getFullYear()+"-"+returnZore(d.getMonth()+1)+"-"+returnZore(d.getDate())+" "+returnZore(d.getHours())+":"+returnZore(d.getMinutes())*!/
  return moment(date).format('YYYY-MM-DD HH:mm')
}

export function formatTimeDate(date) {
  /!* let d = new Date(date)
   return d.getFullYear()+"-"+returnZore(d.getMonth()+1)+"-"+returnZore(d.getDate())+" "+returnZore(d.getHours())+":"+returnZore(d.getMinutes())*!/
  return moment(date).format('HH:mm')
}*/

export function formatNowDate() {
  /* console.log(moment().add(1, 'hours'))
   return moment().add(1, 'hours')*/
}

/* export function getDateBy(date) {
  /!* console.log(date)
  let d = new Date(Date.parse(date.replace(/-/g,"/")))
  /!*let format2 = new Date().format('yyyy-MM-dd HH:mm:ss');
  console.log(format2)*!/
  console.log(d.getFullYear()+"-"+returnZore(d.getMonth()+1)+"-"+returnZore(d.getDate()))
  return d.getFullYear()+"-"+returnZore(d.getMonth()+1)+"-"+returnZore(d.getDate())*!/
  /!* console.log(moment(date).format("YYYY-MM-DD"))*!/
  return moment(date).format('YYYY-MM-DD')
}

export function getRangeDate(date) {
  return moment(date).format('MM-DD HH:mm')
  /!* let d = new Date(date)
  return returnZore(d.getMonth()+1)+"-"+returnZore(d.getDate())+" "+returnZore(d.getHours())+":"+returnZore(d.getMinutes())*!/
}

export function isBeforeDate(date, nData) {
  const d = moment(date).format('YYYY-MM-DD HH:mm:ss')
  let n = ''
  if (nData) {
    n = moment(nData).format('YYYY-MM-DD HH:mm:ss')
  } else {
    n = moment().format('YYYY-MM-DD HH:mm:ss')
  }
  return moment(d).isBefore(n)
  /!* let d = new Date(date)
   return returnZore(d.getMonth()+1)+"-"+returnZore(d.getDate())+" "+returnZore(d.getHours())+":"+returnZore(d.getMinutes())*!/
}

export function getCurrDateMoment() {
  return moment().format('YYYY-MM-DD')
  /!* let d = new Date(date)
   return returnZore(d.getMonth()+1)+"-"+returnZore(d.getDate())+" "+returnZore(d.getHours())+":"+returnZore(d.getMinutes())*!/
}

export function toDateMoment(date) {
  return moment(date).format()
}*/

// 排序
export function compare(property) {
  return function(a, b) {
    const value1 = a[property]
    const value2 = b[property]
    return value1 - value2
  }
}
// 比较大小 如果大小相同 按照创建时间排序
/* export function compareOrg(property) {
  return function(a, b) {
    const value1 = a[property]
    const value2 = b[property]
    if (value1 === value2) {
      return isBeforeDate(a['createdTime'], b['createdTime']) === true ? 1 : -1
    } else {
      return value2 - value1
    }
  }
}*/
// 比较时间大小
/* export function compareTime(property) {
  return function(a, b) {
    const value1 = a[property]
    const value2 = b[property]
    return isBeforeDate(value1, value2) === true ? -1 : 1
  }
}*/
// 返回新对象
export function returnNewData(data) {
  const result = {}
  for (const property in data) {
    result[property] = data[property]
  }
  return result
}
// 图片转化为base64
export function getBase64(file) {
  return new Promise(function(resolve, reject) {
    const reader = new FileReader()
    let imgResult = ''
    reader.readAsDataURL(file)
    reader.onload = function() {
      imgResult = reader.result
    }
    reader.onerror = function(error) {
      reject(error)
    }
    reader.onloadend = function() {
      resolve(imgResult)
    }
  })
}

export function compareASC(property) {
  return function(a, b) {
    const value1 = a[property]
    const value2 = b[property]
    return value1 - value2
  }
}
// 升序
export function compareDESC(property) {
  return function(a, b) {
    const value1 = a[property]
    const value2 = b[property]
    return value2 - value1
  }
}
// 降序
export function compareASCTime(property) {
  return function(a, b) {
    const value1 = a[property]
    const value2 = b[property]
    return value2 - value1
  }
}
// 生成树结构
export function translateDataToTree(data, pid) {
  if (!pid) {
    pid = 'pid'
  }
  const parents = data.filter(value => value[pid] === 0)
  const childrens = data.filter(value => value[pid] !== 0)
  const translator = (parents, childrens) => {
    parents.forEach((parent) => {
      childrens.forEach((current, index) => {
        if (current[pid] === parent.id) {
          const temp = JSON.parse(JSON.stringify(childrens))
          temp.splice(index, 1)
          translator([current], temp)
          typeof parent.children !== 'undefined' ? parent.children.push(current) : parent.children = [current]
        }
      }
      )
    }
    )
  }
  translator(parents, childrens)
  return parents
}

// 过滤相同元素
export function filterName(data) {
  const result = []
  if (data) {
    data.forEach((item, index) => {
      if (index === 0) {
        result.push(item)
      } else {
        const obj = result.filter(it => it === item)
        if (obj.length === 0) {
          result.push(item)
        }
      }
    })
  }
  return result
}

export function toFixed(num, count) {
  num = Number(num)
  let result = num.toFixed(count)
  result += ''
  while (result.substring(0, result.length - 1) * 10 === result * 10) {
    result = result.substring(0, result.length - 1)
  }
  return result
}
